 <!--
* description: 车型配置（含输入框）
* author: duanhy
* createdDate: 2020-12-5
-->
<template>
  <section class="cartypeQuery">
    <el-dialog
      id="cartypeq"
      v-dialogDrag
      title="车型配置"
      :visible.sync="popupsVisible"
      width="50%"
      center
      :append-to-body="true"
      :lock-scroll="true"
      :before-close="handleClose"
    >
      <dialogHeader
        slot="title"
        :title="'车型配置'"
        :style-type="$store.state.app.dialogType"
      />
      <template v-for="comps in coms">
        <div :key="comps.tid" class="filter-container filter-params">
          <h3 v-if="comps.title" :style="styleObj">{{ comps.title }}</h3>
          <el-row ref="vailComponentList1" :gutter="26">
            <component
              :is="comp.component"
              v-for="comp in comps.data.filter(o => o.isMust === true)"
              :ref="comp.isRequire ? comp.isRequire+ comp.compKey : comp.compKey"
              :key="comp.compKey"
              :validrule="comp.validrule"
              :code-field="comp.codeField"
              :text-field="comp.textField"
              :popups-key="comp.compKey"
              :code="formField[comp.codeField]"
              :disabled="comp.disabled"
              :is-require="comp.isRequire"
              :is-mul="comp.isMul"
              :span="comp.span || 24"
              :label-name="comp.labelName"
              :lookuptype="comp.lookuptype"
              :parent-fileds="comp.parentFileds"
              :data-to-object="comp.dataToObj"
              :date-options-type="comp.dateOptionsType"
              :custom-obj="comp.customObj"
              :options="comp.options"
              :o-fields="comp.oFields"
              :other-fields="comp.otherFields"
              :cb="comp.cb"
              @changeCode="getComponentCode"
              @focusCode="getFocusCode"
            />
          </el-row>
        </div>
      </template>
      <el-divider />
      <div
        slot="footer"
        class="dialog-footer"
      >
        <el-button
          size="mini"
          type="primary"
          icon="iconfont  icon-confirm"
          @click="sendCode"
        >{{ $t('sys.button.confirm') }}
        </el-button>
        <!-- 确认 -->
      </div>
    </el-dialog>
  </section>
</template>
<script>

import Vue from 'vue'
import { formMixins } from '@/components/mixins/formMixins'
import api from '@/api/apiVeData'
export default {
  name: 'CarTypeSimple',
  components: {
    lableName: () => import('@/components/lableName'), // 标题溢出样式组件
    dialogHeader: () => import('@/components/dialogHeader') // 弹窗标题,
  },
  mixins: [formMixins],
  props: {
    popupsVisible: { type: Boolean, default: false },
    code: { type: String, default: '' },
    comType: { type: String, default: '' },
    codeField: { type: String, default: '' },
    popupsKey: { type: String, default: '' },
    isMul: { type: Boolean, default: true },
    validrule: {
      type: Object,
      default: () => {}
    }
  },
  beforeRouteEnter(to, from, next) {
    Vue.prototype.$ConfigCache.CacheConfig.initData(
      // 同时加载当前页面和编辑框页面的配置
      [to.path, ''],
      function() {
        next()
      })
  },
  data() {
    const viewPageCode = this.$route.path
    // 绑定事件配置化事件
    this.$ConfigCache.CacheConfig.bindEvent(this, [viewPageCode])
    return {
      // apiStyle: 'restful',
      // ruleSettingShow: false,
      // h3标题行内样式
      configId: '',
      arr: [],
      tableComponents: [],
      genCodeFiled: null,
      styleObj: { borderLeft: null },
      coms: [
        {
          // title: '保险费发票',
          tid: 1,
          data: [
            {
              compKey: 'compKey1',
              labelName: '车系：',
              codeField: 'carSeriesCn',
              oFields: 'carSeriesId,carSeriesCn,carSeriesId',
              customObj: {
                api: api.listOfCarSeries
              },
              component: () => import('@/components/org/commonSelect'),
              type: 'dropdownList',
              isMust: true,
              isRequire: true
            },
            {
              compKey: 'compKey2',
              labelName: '基础车型：',
              codeField: 'carConfigId',
              oFields: 'carConfigId,carConfigCn,carConfigCode',
              disabled: true,
              otherFields: 'carConfigCode',
              parentFileds: 'disabled:carSeriesCn-carConfigId--false,value:carSeriesId-carSeriesCn',
              customObj: {
                listQuery: {
                  carSeriesId: ''
                },
                api: api.queryCarType
              },
              component: () => import('@/components/org/commonSelect'),
              type: 'dropdownList',
              isMust: true,
              isRequire: true
            },
            {
              compKey: 'compKey3',
              labelName: '选装包：',
              codeField: 'optionalPagCode',
              textField: 'optionalPagName',
              oFields: 'optionalPagCode,optionalPagName,optionalPagId',
              disabled: true,
              parentFileds: 'value:carConfigId-carConfigId,disabled:carConfigId-optionalPagCode--false',
              customObj: {
                listQuery: {
                  carConfigId: ''
                },
                api: api.queryCarOptionalPagLinkMessage
              },
              component: () => import('@/components/org/commonSelect'),
              type: 'dropdownList',
              isMust: true,
              isRequire: true
            },
            {
              compKey: 'compKey4',
              labelName: '车身颜色：',
              codeField: 'carColorCode',
              textField: 'carColorName',
              oFields: 'carColorCode,carColorName,carColorId',
              disabled: true,
              parentFileds: 'value:carConfigId|optionalPagCode,disabled:optionalPagCode-carColorCode--false',
              customObj: {
                listQuery: {
                  carConfigId: '',
                  optionalPagCode: ''
                },
                api: api.queryCarColorLinkMessage
              },
              component: () => import('@/components/org/commonSelect'),
              type: 'dropdownList',
              isMust: true,
              isRequire: true
            },
            {
              compKey: 'compKey5',
              labelName: '内饰颜色：',
              codeField: 'carIncolorCode',
              textField: 'carIncolorName',
              disabled: true,
              parentFileds: 'value:carConfigId|optionalPagCode,disabled:optionalPagCode-carIncolorCode--false',
              oFields: 'carIncolorCode,carIncolorName,carIncolorId',
              customObj: {
                listQuery: {
                  carConfigId: '',
                  optionalPagCode: ''
                },
                api: api.queryCarInColorLinkMessage
              },
              component: () => import('@/components/org/commonSelect'),
              type: 'dropdownList',
              isMust: true,
              isRequire: true
            },
            {
              compKey: 'compKey6',
              labelName: '车型配置：',
              codeField: 'ttCode',
              disabled: true,
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              // validrule: {
              //   minlength: 22,
              //   maxlength: 22,
              //   resectMessage: {
              //     minlength: '编码为22位!',
              //     maxlength: '编码为22位!'
              //   }
              // },
              isMust: true,
              isRequire: true
            }
          ]
        }
      ],
      curPopupsVisible: this.popupsVisible,
      formField: null

    }
  },
  watch: {
    formField: {
      handler(newVal) {
        this.configId = newVal.carConfigId
        const that = this
        const fs = []
        if (!newVal['carSeriesCn'] && this.arr.length === 0) {
          return
        } else {
          this.carConfigId(newVal['carSeriesCn'])
          for (let i = 0; i < that.arr.length; i++) {
            if (that.arr[i].carConfigId === newVal.carConfigId) {
              fs.push(JSON.parse(JSON.stringify(that.arr[i].carConfigCode)))
            }
          }
          for (const f in newVal) {
            if (f !== 'ttCode' && f !== 'carConfigId' && f !== 'carSeriesCn' && newVal[f]) {
              fs.push(newVal[f])
            }
          }

          newVal['ttCode'] = fs.join('')
        }
      },
      deep: true
    },
    'formField.carSeriesCn': {
      handler(val) {
        if (!val) {
          this.formField.carConfigId = ''
        }
      }
    },
    'formField.carConfigId': {
      handler(val) {
        if (!val) {
          this.formField.optionalPagCode = ''
          this.formField.carColorCode = ''
          this.formField.carIncolorCode = ''
        }
      }
    },
    popupsVisible: {
      handler(newval) {
        if (newval) {
          const backForm = this.$parent.innerForm
          for (const f in this.formField) {
            this.formField[f] = backForm[f]
          }
        }
      },
      immediate: true
    }
  },
  created() {
    this.tableComponents = this.coms.reduce((pre, cur) => [...pre, ...cur.data], [])
    this.genCodeFiled = this.genUtil(this.tableComponents)
    this.formField = this.genCodeFiled('codeField')
  },

  mounted() {
    this.setColor()
  },
  methods: {
    // 根据车系id查车型
    carConfigId(id) {
      const returnObj = {
      // api配置
        apiConfig: api.queryCarType,
        variables: {
          carSeriesId: id
        }
      }
      var paramD = this.$getParams(returnObj, null, this.dynamicApiStyle)
      this.$requestAPI(paramD, this.dynamicApiStyle).then(response => {
        if (response.result === '0') {
          if (response.msg) {
            this.$message({
              message: response.msg,
              type: 'warn',
              duration: 2000
            })
          }
          return
        } else {
          this.arr = JSON.parse(JSON.stringify(response.rows))
        }
      }).catch(err => {
        console.info(err)
      })
    },
    onCreated() {
      if (this.formField === null) {
        this.formField = { carBrandCode: '' }
      }
    },
    // 获取数据
    sendCode() {
      this.$utils.validataMoth(this, 'validpopup')
      if (this.valid) {
        // let res = {}
        const creationForm = this.$parent.$parent.$parent.$parent.formField
        creationForm['carConfigId'] = this.configId
        for (const ref in this.$refs) {
          if (ref.includes('true')) {
            const ops = this.$refs[ref][0].optionDatas
            let fieldId
            let codeField
            if (this.$refs[ref][0].oFields) {
              fieldId = this.$refs[ref][0].oFields.split(',')[2]
              codeField = this.$refs[ref][0].oFields.split(',')[0]
            }
            if (ops && fieldId) {
              ops.forEach(o => {
                if (this.formField[codeField] === o[codeField]) {
                  if (fieldId === 'optionalPagId') {
                    creationForm['carOptionalpagId'] = o[fieldId]
                  } else {
                    creationForm[fieldId] = o[fieldId]
                  }
                }
              })
            }
          }
        }
        creationForm['carSerId'] = this.formField.carSeriesCn
        const ttCode = this.formField.ttCode
        this.$parent.innerForm = this.$utils.deepCopy(this.formField)
        this.$parent.modelCode = ttCode
        this.$parent.modelText = ttCode
        this.$emit('update:popups-visible', false)
      }
    },
    genUtil: (array) => (attr) => array.reduce((p, c) => {
      p[c[attr]] = ''
      return p
    }, {}),
    // 设置h3标题颜色
    setColor() {
      const nowSystemColor = this.$store.getters.nowTheme.backgroundColor
      this.styleObj.borderLeft = `5px solid ${nowSystemColor}`
    },
    // 控制选择禁用状态 车系为空则其它选项禁用
    // handleDisable(vehicle, formFields) {
    //   !vehicle ? this.resetForm(formFields) : ''
    //   this.tableComponents.forEach(dropdownList => {
    //     if (dropdownList.codeField !== 'carconfig') { dropdownList.hasOwnProperty('disabled') ? dropdownList.disabled = vehicle === '' : '' }
    //   })
    // },
    // 隐藏(重置)验证图标
    resetIconV() {
      this.$nextTick(() => {
        for (const comp in this.$refs) {
          if (comp.includes('true')) {
            this.$refs[comp][0].$children[0].$children[2].iconV = '3'
          }
        }
      })
    },
    // 重置所有选择
    resetForm(formFields) {
      for (const attr in formFields) {
        formFields[attr] = ''
      }
      this.resetIconV()
    },
    handleClose() {
      this.$confirm(`确认关闭？`)
        .then(_ => {
          const data = this.$utils.deepCopy(this.formField)
          this.$parent.innerForm = data
          this.$emit('update:popupsVisible', false)
          done()
        })
        .catch(_ => {})
    }

  }
}
</script>

<style lang="css" scoped>
  h3 {
    padding-left: 10px;
    text-align: left;
    font-weight: 600;
  }

  h3 button.el-button {
    float: right;
    margin-right: 10px;
  }
  >>> div.el-col.el-col-24 {
    margin-bottom: 10px;
  }
</style>
